package com.springboot.demo.module.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.springboot.demo.core.constant.CodeMsg;
import com.springboot.demo.core.exception.CosyException;
import com.springboot.demo.core.utils.SysUtils;
import com.springboot.demo.module.entity.TSysUser;
import com.springboot.demo.module.mapper.UserMapper;
import com.springboot.demo.module.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * 用户service实现类
 * @author Francis
 * @Date 11:54 2019-02-24
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, TSysUser> implements IUserService {

    @Autowired
    private UserMapper userMapper;


    @Override
    public Boolean addUser(TSysUser user) {
        //1. 查重
        int count = this.count(new QueryWrapper<TSysUser>().eq("login_name", user.getLoginName()));
        if(count > 0){
            log.error("登录名重复");
            throw new CosyException(CodeMsg.LOGIN_NAME_HAS_EXIST);
        }

        //2. 加密 && 入库
        String encodePassword = SysUtils.encodeByMd5(user.getUserPassword());
        user.setUserPassword(encodePassword);
        boolean addFlag = false;
        try {
            addFlag = this.save(user);
        } catch (Exception e) {
            log.error("插入新用户过程中出现异常！", e);
            throw new CosyException(CodeMsg.DB_ERROR);
        }

        return addFlag;
    }
}
